<template>
  <div class="sensitive-word-page">
    <!-- 面包屑导航 -->
    <div class="header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item to="/home">{{ t('menu.home') }}</el-breadcrumb-item>
        <el-breadcrumb-item>{{ t('sensitive.title') }}</el-breadcrumb-item>
      </el-breadcrumb>
      <div class="actions">
        <el-button type="primary" @click="showAddDialog = true">
          <el-icon><Plus /></el-icon>
          {{ t('sensitive.addKeyword') }}
        </el-button>
          <el-button 
            type="success" 
            @click="startCheck"
            :loading="checking"
            :disabled="keywords.length === 0"
          >
            <el-icon><Search /></el-icon>
            {{ checking ? t('sensitive.checking') : t('sensitive.startCheck') }}
          </el-button>
          <el-button type="info" @click="clearResults" v-if="checkResults.length > 0">
            {{ t('sensitive.clearResults') }}
          </el-button>
      </div>
    </div>

    <el-row :gutter="20">
      <!-- 左侧：敏感词管理 -->
      <el-col :span="5">
        <el-card class="keyword-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">{{ t('sensitive.keywordManagement') }}</span>
              <el-tag type="info" size="small">{{ t('sensitive.total') }} {{ keywords.length }} {{ t('sensitive.count') }}</el-tag>
            </div>
          </template>

          <div class="keyword-management">
            <!-- 分类选择 -->
            <div class="category-section">
              <el-select v-model="selectedCategory" :placeholder="t('sensitive.selectCategory')" style="width: 100%;">
                <el-option 
                  v-for="category in categories" 
                  :key="category"
                  :label="`${category} (${getKeywordCount(category)})`"
                  :value="category"
                />
              </el-select>
            </div>

            <!-- 敏感词列表 -->
            <div class="keyword-list">
              <div 
                v-for="keyword in filteredKeywords" 
                :key="keyword.id"
                class="keyword-item"
              >
                <span class="keyword-text">{{ keyword.word }}</span>
                <div class="keyword-actions">
                  <el-button type="text" size="small" @click="editKeyword(keyword)">{{ t('sensitive.edit') }}</el-button>
                  <el-button type="text" size="small" @click="deleteKeyword(keyword.id)" class="delete-btn">{{ t('sensitive.delete') }}</el-button>
                </div>
              </div>
              
              <div v-if="filteredKeywords.length === 0" class="empty-state">
                <el-empty :description="t('sensitive.noKeywords')" :image-size="80" />
              </div>
            </div>

            <!-- 批量操作 -->
            <div class="batch-actions">
              <el-upload
                :before-upload="handleFileImport"
                :show-file-list="false"
                accept=".txt,.csv"
              >
                <el-button type="success" plain size="small">
                  <el-icon><Upload /></el-icon>
                  {{ t('sensitive.batchImport') }}
                </el-button>
              </el-upload>
              <el-button type="warning" plain size="small" @click="exportKeywords">
                <el-icon><Download /></el-icon>
                {{ t('sensitive.export') }}
              </el-button>
            </div>
          </div>
        </el-card>

        <!-- 系统状态 -->
        <el-card class="status-card" shadow="never" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span class="card-title">{{ t('sensitive.systemStatus') }}</span>
            </div>
          </template>
          <div class="status-info">
            <div class="status-item">
              <span class="status-label">{{ t('sensitive.databaseConnection') }}</span>
              <el-tag :type="checkConfig.databaseId ? 'success' : 'info'" size="small">
                {{ checkConfig.databaseId ? t('sensitive.connected') : t('sensitive.notSelected') }}
              </el-tag>
            </div>
            <div class="status-item">
              <span class="status-label">{{ t('sensitive.keywordLibrary') }}</span>
              <el-tag type="primary" size="small">{{ keywords.length }} {{ t('sensitive.count') }}</el-tag>
            </div>
            <div class="status-item">
              <span class="status-label">{{ t('sensitive.checkMode') }}</span>
              <el-tag type="info" size="small">{{ checkConfig.mode === 'full' ? t('sensitive.fullCheck') : t('sensitive.selectiveCheck') }}</el-tag>
            </div>
            <div v-if="checkResults.length > 0" class="status-item">
              <span class="status-label">{{ t('sensitive.foundIssues') }}</span>
              <el-tag type="danger" size="small">{{ checkResults.length }} {{ t('sensitive.count') }}</el-tag>
            </div>
          </div>
        </el-card>

        <!-- 快速操作 -->
        <el-card class="quick-actions-card" shadow="never" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span class="card-title">{{ t('sensitive.quickActions') }}</span>
            </div>
          </template>
          <div class="quick-actions">
            <el-button type="primary" size="small" block @click="showAddDialog = true">
              <el-icon><Plus /></el-icon>
              {{ t('sensitive.addKeyword') }}
            </el-button>
            <el-button v-if="checkResults.length > 0" type="success" size="small" block @click="exportResults">
              <el-icon><Download /></el-icon>
              {{ t('sensitive.exportResults') }}
            </el-button>
            <el-button v-if="checkResults.length > 0" type="warning" size="small" block @click="clearResults">
              {{ t('sensitive.clearResults') }}
            </el-button>
          </div>
        </el-card>

        <!-- 历史任务 -->
        <el-card class="history-tasks-card" shadow="never" style="margin-top: 20px;">
          <template #header>
            <div class="card-header">
              <span class="card-title">{{ t('sensitive.historyTasks') }}</span>
              <el-button type="text" size="small" @click="loadHistoryTasks" :loading="loadingTasks">
                <el-icon><Refresh /></el-icon>
                {{ t('sensitive.refresh') }}
              </el-button>
            </div>
          </template>
          <div class="history-tasks">
            <div v-if="loadingTasks" class="task-loading">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>{{ t('sensitive.loading') }}</span>
            </div>
            <div v-else-if="historyTasks.length === 0" class="no-tasks">
              {{ t('sensitive.noTasks') }}
            </div>
            <div v-else class="task-list">
              <div 
                v-for="task in historyTasks" 
                :key="task.taskId"
                class="task-item"
                :class="{ 'active': selectedTaskId === task.taskId }"
                @click="selectTask(task)"
              >
                <div class="task-info">
                  <div class="task-name">{{ task.taskName }}</div>
                  <div class="task-meta">
                    <el-tag 
                      :type="getTaskStatusType(task.status)" 
                      size="small"
                    >
                      {{ getTaskStatusText(task.status) }}
                    </el-tag>
                    <span class="task-time">{{ formatTaskTime(task.createTime) }}</span>
                  </div>
                  <div class="task-stats">
                    <span>{{ task.foundIssues || 0 }} {{ t('sensitive.issues') }}</span>
                    <span v-if="task.elapsedTime">{{ t('sensitive.elapsedTime') }} {{ task.elapsedTime }}s</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：检查配置和结果 -->
      <el-col :span="19">
        <!-- 检查配置 -->
        <el-card class="check-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">{{ t('sensitive.checkConfig') }}</span>
              <el-tag v-if="checkConfig.databaseId" type="success" size="small">
                {{ t('sensitive.connected') }}
              </el-tag>
            </div>
          </template>

          <div class="check-configuration">
            <el-form :model="checkConfig" label-width="100px" size="default" class="config-form">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item :label="t('sensitive.database')">
                    <el-select 
                      v-model="checkConfig.databaseId" 
                      :placeholder="t('sensitive.selectDatabase')" 
                      style="width: 100%;"
                      @change="onDatabaseChange">
                      <el-option 
                        v-for="db in databases" 
                        :key="db.id"
                        :label="db.name"
                        :value="db.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item :label="t('sensitive.mode')">
                    <el-radio-group v-model="checkConfig.mode" @change="onModeChange">
                      <el-radio value="full">{{ t('sensitive.fullMode') }}</el-radio>
                      <el-radio value="selective">{{ t('sensitive.selectiveMode') }}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 目标表选择 -->
              <div v-if="checkConfig.databaseId && checkConfig.mode === 'selective'" class="table-selection-section">
                <el-collapse v-model="tableSelectionExpanded">
                  <el-collapse-item :title="t('sensitive.targetTables')" name="tables">
                    <template #title>
                      <div class="collapse-title">
                        <span>{{ t('sensitive.targetTables') }}</span>
                        <el-tag size="small" v-if="selectedTables.length > 0">
                          {{ t('sensitive.selected') }} {{ selectedTables.length }} {{ t('sensitive.tables') }}
                        </el-tag>
                      </div>
                    </template>
                    
                    <div class="table-transfer-container">
                      <div class="transfer-header">
                        <div class="transfer-info">
                          <span>{{ t('sensitive.targetTables') }} ({{ selectedTables.length }}/{{ availableTables.length }})</span>
                          <el-tag size="small" type="success">{{ t('sensitive.filteredSystemTables') }}</el-tag>
                        </div>
                        <el-button size="small" icon="Refresh" @click="loadTables" :loading="loadingTables">{{ t('sensitive.refresh') }}</el-button>
                      </div>
                      
                      <el-transfer
                        v-model="selectedTables"
                        :data="transferData"
                        :titles="[t('sensitive.availableTables'), t('sensitive.selectedTables')]"
                        :button-texts="[t('sensitive.removeTable'), t('sensitive.addTable')]"
                        :format="{
                          noChecked: '${total}',
                          hasChecked: '${checked}/${total}'
                        }"
                        filterable
                        :filter-placeholder="t('sensitive.searchTable')"
                        style="text-align: left; display: inline-block"
                        v-loading="loadingTables"
                      >
                        <template #default="{ option }">
                          <div class="transfer-item">
                            <el-icon class="table-icon"><Grid /></el-icon>
                            <div class="table-content">
                              <div class="table-name">{{ option.label }}</div>
                              <div class="table-comment" v-if="option.comment">{{ option.comment }}</div>
                            </div>
                          </div>
                        </template>
                      </el-transfer>
                      
                      <el-empty v-if="!loadingTables && availableTables.length === 0" :description="t('sensitive.noTables')" />
                    </div>
                  </el-collapse-item>
                </el-collapse>
              </div>

              <!-- 高级选项 -->
              <div class="advanced-options">
                <el-collapse>
                  <el-collapse-item :title="t('sensitive.advancedConfig')" name="advanced">
                    <el-row :gutter="20">
                      <el-col :span="8">
                        <el-form-item :label="t('sensitive.batchSize')">
                          <el-input-number v-model="checkConfig.batchSize" :min="100" :max="5000" style="width: 100%;" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item :label="t('sensitive.concurrency')">
                          <el-input-number v-model="checkConfig.concurrency" :min="1" :max="5" style="width: 100%;" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="8">
                        <el-form-item :label="t('sensitive.timeout')">
                          <el-input-number v-model="checkConfig.timeout" :min="5" :max="60" style="width: 100%;" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="24">
                        <el-form-item>
                          <el-checkbox v-model="checkConfig.caseSensitive">{{ t('sensitive.caseSensitive') }}</el-checkbox>
                          <el-checkbox v-model="checkConfig.useReadReplica">{{ t('sensitive.useReadReplica') }}</el-checkbox>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </el-form>

            <!-- 检查进度 -->
            <div v-if="checking" class="progress-section">
              <el-progress 
                :percentage="progress.percentage" 
                :status="progress.status"
                :stroke-width="6"
              />
              <div class="progress-info">
                <p>{{ progress.message }}</p>
                <div class="progress-stats">
                  <span>{{ t('sensitive.checkedTables') }}: {{ progress.checkedTables }}/{{ progress.totalTables }} {{ t('sensitive.tables') }}</span>
                  <span>{{ t('sensitive.foundProblems') }}: {{ progress.foundIssues }} {{ t('sensitive.count') }}</span>
                  <span>{{ t('sensitive.elapsedTime') }}: {{ formatTime(progress.elapsedTime) }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 检查结果 -->
        <el-card v-if="checkResults.length > 0" class="results-card" shadow="never">
          <template #header>
            <div class="card-header">
              <span class="card-title">{{ t('sensitive.checkResults') }}</span>
              <div class="result-actions">
                <el-tag type="danger">{{ t('sensitive.totalIssues') }}: {{ checkResults.length }}</el-tag>
                <el-button type="success" size="small" @click="exportResults">
                  <el-icon><Download /></el-icon>
                  {{ t('sensitive.exportResults') }}
                </el-button>
              </div>
            </div>
          </template>

          <div class="check-results">
            <!-- 结果统计 -->
            <div class="result-summary">
              <el-row :gutter="20">
                <el-col :span="12">
                  <h4>{{ t('sensitive.byCategory') }}</h4>
                  <div class="stats-list">
                    <div v-for="(count, category) in categoryStats" :key="category" class="stats-item">
                      <span>{{ category }}</span>
                      <el-tag :type="getTagType(category)" size="small">{{ count }}</el-tag>
                    </div>
                  </div>
                </el-col>
                <el-col :span="12">
                  <h4>{{ t('sensitive.byTable') }}</h4>
                  <div class="stats-list">
                    <div v-for="(count, table) in tableStats" :key="table" class="stats-item">
                      <span>{{ table }}</span>
                      <el-tag type="info" size="small">{{ count }}</el-tag>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>

            <!-- 批量操作区域 -->
            <div v-if="checkResults.length > 0" class="batch-operations" style="margin-bottom: 16px;">
              <el-row :gutter="12">
                <el-col :span="12">
                  <el-button type="danger" size="small" @click="batchIgnoreSelected">
                    <el-icon><Delete /></el-icon>
                    {{ t('sensitive.batchIgnoreSelected') }}
                  </el-button>
                  <el-button type="warning" size="small" @click="batchGenerateSQL">
                    <el-icon><Document /></el-icon>
                    {{ t('sensitive.batchGenerateSQL') }}
                  </el-button>
                </el-col>
                <el-col :span="12" style="text-align: right;">
                  <el-button type="success" size="small" @click="exportResultsFile">
                    <el-icon><Download /></el-icon>
                    {{ t('sensitive.exportResults') }}
                  </el-button>
                  <el-button type="info" size="small" @click="showStatistics">
                    <el-icon><DataAnalysis /></el-icon>
                    {{ t('sensitive.viewStatistics') }}
                  </el-button>
                </el-col>
              </el-row>
            </div>

            <!-- 结果表格 -->
            <div class="results-table">
              <el-table 
                :data="paginatedResults" 
                stripe 
                style="width: 100%" 
                :max-height="500"
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="tableName" :label="t('sensitive.table')" width="120" />
                <el-table-column prop="columnName" :label="t('sensitive.column')" width="120" />
                <el-table-column prop="recordId" :label="t('sensitive.id')" width="100" />
                <el-table-column prop="keyword" :label="t('sensitive.sensitiveWord')" width="100">
                  <template #default="scope">
                    <el-tag :type="getTagType(scope.row.category)" size="small">
                      {{ scope.row.keyword }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="category" :label="t('sensitive.category')" width="100" />
                <el-table-column prop="context" :label="t('sensitive.context')" show-overflow-tooltip>
                  <template #default="scope">
                    <div class="context-text" :title="scope.row.context">
                      {{ scope.row.context }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column :label="t('sensitive.action')" width="220" fixed="right">
                  <template #default="scope">
                    <div class="table-actions">
                      <el-button type="text" size="small" @click="viewRecord(scope.row)">{{ t('sensitive.view') }}</el-button>
                      <el-button type="text" size="small" @click="generateSQL(scope.row)">{{ t('sensitive.generateSQL') }}</el-button>
                      <el-button type="text" size="small" @click="ignoreResult(scope.row.id)">{{ t('sensitive.ignore') }}</el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>

            <!-- 分页 -->
            <div class="pagination">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="checkResults.length"
                layout="total, sizes, prev, pager, next, jumper"
              />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加/编辑敏感词对话框 -->
    <el-dialog v-model="showAddDialog" :title="editingKeyword ? t('sensitive.editKeywordTitle') : t('sensitive.addKeywordTitle')" width="400px" class="keyword-dialog">
      <el-form :model="keywordForm" :rules="keywordRules" ref="keywordFormRef" class="dialog-form">
        <el-form-item :label="t('sensitive.keyword')" prop="word">
          <el-input v-model="keywordForm.word" :placeholder="t('sensitive.enterKeyword')" />
        </el-form-item>
        <el-form-item :label="t('sensitive.category')" prop="category">
          <el-select v-model="keywordForm.category" :placeholder="t('sensitive.selectCategoryPlaceholder')" style="width: 100%">
            <el-option v-for="category in categories" :key="category" :label="category" :value="category" />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('sensitive.description')">
          <el-input v-model="keywordForm.description" type="textarea" :placeholder="t('sensitive.descriptionPlaceholder')" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">{{ t('common.cancel') }}</el-button>
        <el-button type="primary" @click="saveKeyword">{{ t('common.save') }}</el-button>
      </template>
    </el-dialog>

    <!-- 记录详情对话框 -->
    <el-dialog v-model="showDetailDialog" :title="t('sensitive.recordDetail')" width="600px" class="detail-dialog">
      <div v-if="selectedRecord" class="record-details">
        <el-descriptions :column="2" border>
          <el-descriptions-item :label="t('sensitive.tableName')">{{ selectedRecord.tableName }}</el-descriptions-item>
          <el-descriptions-item :label="t('sensitive.columnName')">{{ selectedRecord.columnName }}</el-descriptions-item>
          <el-descriptions-item :label="t('sensitive.recordId')">{{ selectedRecord.recordId }}</el-descriptions-item>
          <el-descriptions-item :label="t('sensitive.sensitiveWord')">{{ selectedRecord.keyword }}</el-descriptions-item>
          <el-descriptions-item :label="t('sensitive.category')">{{ selectedRecord.category }}</el-descriptions-item>
          <el-descriptions-item :label="t('sensitive.foundTime')">{{ selectedRecord.createdAt }}</el-descriptions-item>
        </el-descriptions>
        
        <h4>{{ t('sensitive.fullContent') }}</h4>
        <el-input :model-value="selectedRecord.fullContent" type="textarea" :rows="4" readonly />
        
        <h4>{{ t('sensitive.querySQL') }}</h4>
        <el-input :model-value="selectedRecord.sqlQuery" readonly />
        
        <div class="record-actions">
          <el-button @click="copySQL(selectedRecord.sqlQuery)">{{ t('sensitive.copySQL') }}</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 清理SQL对话框 -->
    <el-dialog v-model="showSQLDialog" :title="t('sensitive.generateCleanSQL')" width="600px" class="sql-dialog">
      <div v-if="selectedRecord" class="sql-content">
        <div class="action-selection">
          <el-radio-group v-model="cleanAction">
            <el-radio value="replace">{{ t('sensitive.replaceWith') }}</el-radio>
            <el-radio value="delete">{{ t('sensitive.deleteRecord') }}</el-radio>
            <el-radio value="clear">{{ t('sensitive.clearField') }}</el-radio>
          </el-radio-group>
        </div>
        
        <h4>{{ t('sensitive.generatedSQL') }}</h4>
        <el-input v-model="generatedSQL" type="textarea" :rows="4" readonly />
        
        <el-alert 
          :title="t('sensitive.warningBackup')" 
          type="warning" 
          :closable="false"
          class="warning-alert"
        />
      </div>
      <template #footer>
        <el-button @click="showSQLDialog = false">{{ t('common.cancel') }}</el-button>
        <el-button @click="copySQL(generatedSQL)">{{ t('sensitive.copySQL') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useI18n } from 'vue-i18n'
import api from '@/api'
// import { mockSensitiveWordAPI } from '@/mock/sensitiveWord' // 开发时使用mock数据

const { t } = useI18n()

// 响应式数据
const keywords = ref([])
const categories = ref([]) // 动态从后端加载
const selectedCategory = ref('')
const databases = ref([])
const checkResults = ref([])
const checking = ref(false)

// 表选择相关
const availableTables = ref([])
const selectedTables = ref([])
const loadingTables = ref(false)
const tableSelectionExpanded = ref(['tables']) // 默认展开

// 表过滤配置
const tableFilterConfig = {
  // 系统表前缀
  systemPrefixes: [
    'information_schema', 'performance_schema', 'mysql', 'sys',
    'temp_', 'tmp_', 'bak_', '_bak', 'backup_', '_backup',
    'test_', '_test', 'demo_', '_demo'
  ],
  // 日志表关键词
  logKeywords: [
    'log', 'logs', '_log', '_logs', 'audit', '_audit',
    'history', '_history', '_his', 'trace', '_trace'
  ],
  // 配置表关键词
  configKeywords: [
    'config', '_config', 'setting', '_setting', 'param', '_param',
    'dict', '_dict', 'dictionary', 'meta', '_meta'
  ],
  // 系统表关键词
  systemKeywords: [
    'session', '_session', 'cache', '_cache', 'queue', '_queue',
    'sequence', '_sequence', 'privilege', '_privilege', 'role', '_role'
  ]
}

// 表过滤函数
const filterBusinessTables = (tables) => {
  return tables.filter(table => {
    const tableName = table.tableName.toLowerCase()
    
    // 检查系统表前缀
    if (tableFilterConfig.systemPrefixes.some(prefix => 
      tableName.startsWith(prefix.toLowerCase())
    )) {
      return false
    }
    
    // 检查各种系统表关键词
    const allKeywords = [
      ...tableFilterConfig.logKeywords,
      ...tableFilterConfig.configKeywords,
      ...tableFilterConfig.systemKeywords
    ]
    
    if (allKeywords.some(keyword => 
      tableName.includes(keyword.toLowerCase())
    )) {
      return false
    }
    
    return true
  })
}

// Transfer组件数据
const transferData = computed(() => {
  return availableTables.value.map(table => ({
    key: table.tableName,
    label: table.tableName,
    comment: table.tableComment || '业务表',
    engine: table.engine,
    charset: table.charset
  }))
})

// 检查配置
const checkConfig = ref({
  databaseId: '',
  mode: 'full',
  batchSize: 1000,
  concurrency: 3,
  timeout: 30,
  caseSensitive: false,
  useReadReplica: true
})

// 进度信息
const progress = ref({
  percentage: 0,
  status: '',
  message: '',
  checkedTables: 0,
  totalTables: 0,
  foundIssues: 0,
  elapsedTime: 0
})

// 对话框状态
const showAddDialog = ref(false)
const showDetailDialog = ref(false)
const showSQLDialog = ref(false)
const editingKeyword = ref(null)
const selectedRecord = ref(null)

// 表单数据
const keywordForm = ref({
  word: '',
  category: '不文明词语',
  description: ''
})

const keywordRules = {
  word: [{ required: true, message: () => t('sensitive.keywordRequired'), trigger: 'blur' }],
  category: [{ required: true, message: () => t('sensitive.categoryRequired'), trigger: 'change' }]
}

// 分页
const currentPage = ref(1)
const pageSize = ref(20)

// 清理相关
const cleanAction = ref('replace')
const generatedSQL = ref('')

// 历史任务相关
const historyTasks = ref([])
const selectedTaskId = ref(null)
const loadingTasks = ref(false)

// 批量操作相关
const selectedResults = ref([])


// 计算属性
const filteredKeywords = computed(() => {
  return keywords.value.filter(k => k.category === selectedCategory.value)
})

const getKeywordCount = (category) => {
  return keywords.value.filter(k => k.category === category).length
}

const categoryStats = computed(() => {
  const stats = {}
  checkResults.value.forEach(result => {
    stats[result.category] = (stats[result.category] || 0) + 1
  })
  return stats
})

const tableStats = computed(() => {
  const stats = {}
  checkResults.value.forEach(result => {
    stats[result.tableName] = (stats[result.tableName] || 0) + 1
  })
  return stats
})

const paginatedResults = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return checkResults.value.slice(start, end)
})


// 方法
const loadKeywords = async () => {
  try {
    console.log('📝 加载敏感词列表...')
    const response = await api.sensitiveWord.getKeywords()
    
    // 处理不同的响应数据结构
    let data = response.data
    if (Array.isArray(response.data?.records)) {
      // 分页数据结构
      data = response.data.records
    } else if (Array.isArray(response.data)) {
      // 直接数组结构
      data = response.data
    } else {
      data = []
    }
    
    keywords.value = data
    console.log('加载的敏感词数量:', data.length)
    console.log('敏感词分类统计:', data.reduce((acc, item) => {
      acc[item.category] = (acc[item.category] || 0) + 1
      return acc
    }, {}))
    
    if (data.length === 0) {
      console.log('📝 暂无敏感词数据')
    } else {
      console.log(`✅ 成功加载 ${data.length} 个敏感词`)
    }
  } catch (error) {
    console.error('❌ 敏感词加载失败:', error)
    throw error // 让上层处理
  }
}

const loadDatabases = async () => {
  try {
    console.log('💾 加载数据库配置...')
    const response = await api.database.getDatabases()
    
    // 处理不同的响应数据结构
    let data = response.data
    if (Array.isArray(response.data?.records)) {
      // 分页数据结构
      data = response.data.records
    } else if (Array.isArray(response.data)) {
      // 直接数组结构
      data = response.data
    } else {
      data = []
    }
    
    databases.value = data
    console.log('加载的数据库配置数量:', data.length)
    
    if (data.length > 0 && data[0].id != null && data[0].id !== undefined) {
      checkConfig.value.databaseId = data[0].id
      console.log(`✅ 成功加载 ${data.length} 个数据库配置，默认选择: ${data[0].id}`)
    } else {
      checkConfig.value.databaseId = ''
      if (data.length === 0) {
        console.log('💾 暂无数据库配置')
      } else {
        console.warn('💾 数据库配置数据异常:', data)
      }
    }
  } catch (error) {
    console.error('❌ 数据库配置加载失败:', error)
    throw error // 让上层处理
  }
}

const saveKeyword = async () => {
  try {
    if (editingKeyword.value) {
      await api.sensitiveWord.updateKeyword(editingKeyword.value.id, keywordForm.value)
      ElMessage.success(t('sensitive.updateSuccess'))
    } else {
      await api.sensitiveWord.addKeyword(keywordForm.value)
      ElMessage.success(t('sensitive.addSuccess'))
    }
    
    showAddDialog.value = false
    editingKeyword.value = null
    keywordForm.value = { word: '', category: categories.value[0] || '不文明词语', description: '' }
    
    // 延迟一点再加载，避免与其他操作冲突
    setTimeout(() => {
      loadKeywords()
    }, 100)
  } catch (error) {
    ElMessage.error(t('sensitive.saveFailed'))
  }
}

const editKeyword = (keyword) => {
  editingKeyword.value = keyword
  // 复制数据到表单，确保分类是中文的
  keywordForm.value = { 
    ...keyword,
    category: keyword.category // 已经是中文分类了
  }
  showAddDialog.value = true
}

const deleteKeyword = async (id) => {
  try {
    await ElMessageBox.confirm(t('sensitive.confirmDelete'), t('sensitive.confirmDeleteTitle'), { type: 'warning' })
    await api.sensitiveWord.deleteKeyword(id)
    ElMessage.success(t('sensitive.deleteSuccess'))
    
    // 延迟一点再加载，避免与其他操作冲突
    setTimeout(() => {
      loadKeywords()
    }, 100)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(t('sensitive.deleteFailed'))
    }
  }
}

const startCheck = async () => {
  if (keywords.value.length === 0) {
    ElMessage.warning(t('sensitive.pleaseAddKeywords'))
    return
  }
  
  if (!checkConfig.value.databaseId) {
    ElMessage.warning(t('sensitive.pleaseSelectDatabase'))
    return
  }
  
  checking.value = true
  progress.value = {
    percentage: 0,
    status: '',
    message: t('sensitive.preparing'),
    checkedTables: 0,
    totalTables: 0,
    foundIssues: 0,
    elapsedTime: 0
  }
  
  try {
    // 验证用户选择
    if (!checkConfig.value.databaseId) {
      ElMessage.warning(t('sensitive.pleaseSelectDatabase'))
      checking.value = false
      return
    }
    
    // 验证表选择（只有选择性模式需要验证）
    if (checkConfig.value.mode === 'selective' && selectedTables.value.length === 0) {
      ElMessage.warning(t('sensitive.pleaseSelectTables'))
      checking.value = false
      return
    }
    
    if (keywords.value.length === 0) {
      ElMessage.warning(t('sensitive.noKeywordsAvailable'))
      checking.value = false
      return
    }
    
    // 构造检查任务请求数据
    const targetTables = checkConfig.value.mode === 'full' 
      ? [] // 全量模式，后端处理所有表
      : selectedTables.value // 选择性模式，使用用户选择的表
      
    // 验证数据库ID是否有效
    const databaseId = checkConfig.value.databaseId
    if (!databaseId || databaseId === '' || databaseId === 'undefined') {
      ElMessage.warning(t('sensitive.pleaseSelectValidDatabase'))
      checking.value = false
      return
    }
    
    const parsedDatabaseId = parseInt(databaseId)
    if (isNaN(parsedDatabaseId)) {
      ElMessage.warning(t('sensitive.invalidDatabaseId'))
      checking.value = false
      return
    }
    
    const requestData = {
      taskName: `${checkConfig.value.mode === 'full' ? '全量' : '选择性'}敏感词检查_${new Date().toLocaleString()}`,
      databaseId: parsedDatabaseId, // 转换为数字
      targetTables: targetTables,
      keywordIds: keywords.value.map(k => k.id), // 使用敏感词ID列表
      batchSize: checkConfig.value.batchSize || 1000,
      checkConfig: {
        caseSensitive: checkConfig.value.caseSensitive,
        fuzzyMatch: false,
        maxResults: 10000,
        contextLength: 50,
        includeDeleted: false
      }
    }
    
    console.log('发送检查请求数据:', requestData)
    const response = await api.checkTask.startCheck(requestData)
    
    // 验证任务ID的有效性 - 后端现在返回字符串格式的taskId避免JavaScript精度问题
    const taskId = response.data
    console.log('后端返回的完整响应:', response)
    console.log('提取的taskId:', taskId, typeof taskId)
    
    if (!taskId || taskId === 'undefined' || typeof taskId !== 'string' || taskId.trim() === '') {
      ElMessage.error(t('sensitive.taskCreationFailed'))
      checking.value = false
      return
    }
    
    // taskId 现在已经是字符串格式，直接使用
    const taskIdStr = taskId.trim()
    
    console.log('任务创建成功，任务ID:', taskId)
    
    // 定义轮询定时器变量
    let progressTimer = null
    
    // 轮询进度
    const pollProgress = async () => {
      try {
        const progressResponse = await api.checkTask.getProgress(taskIdStr)
        const progressData = progressResponse.data
        
        progress.value = progressData
        
        if (progressData.status === 'completed') {
          progress.value.status = 'success'
          
          // 加载结果
          const resultResponse = await api.result.getByTaskId(taskIdStr)
          checkResults.value = resultResponse.data
          
          // 显示完成状态2秒后隐藏进度条
          setTimeout(() => {
            checking.value = false
            ElMessage.success(t('sensitive.checkCompleted', { count: checkResults.value.length }))
            // 刷新历史任务列表
            loadHistoryTasks()
          }, 2000)
          
          if (progressTimer) {
            clearInterval(progressTimer)
            progressTimer = null
          }
        } else if (progressData.status === 'failed') {
          checking.value = false
          progress.value.status = 'exception'
          ElMessage.error(t('sensitive.checkFailed'))
          if (progressTimer) {
            clearInterval(progressTimer)
            progressTimer = null
          }
        }
      } catch (error) {
        console.error('轮询任务进度失败:', error)
        // 如果是参数错误或任务不存在，立即停止轮询
        if (error.response?.status === 400 || error.response?.status === 404 || 
            error.message?.includes('undefined') || error.message?.includes('任务不存在')) {
          if (progressTimer) {
            clearInterval(progressTimer)
            progressTimer = null
          }
          checking.value = false
          ElMessage.error(t('sensitive.checkFailed') + '：' + (error.response?.data?.message || error.message || '参数错误'))
          return
        }
        // 其他错误可能是临时网络问题，继续轮询但记录错误
        console.warn('轮询遇到临时错误，将继续重试:', error.message)
      }
    }
    
    // 启动轮询
    progressTimer = setInterval(pollProgress, 2000)
    
    // 设置超时
    setTimeout(() => {
      if (checking.value && progressTimer) {
        clearInterval(progressTimer)
        progressTimer = null
        checking.value = false
        ElMessage.error(t('sensitive.checkTimeout'))
      }
    }, checkConfig.value.timeout * 60 * 1000)
    
  } catch (error) {
    checking.value = false
    ElMessage.error(t('sensitive.startCheckFailed'))
  }
}

const viewRecord = (record) => {
  selectedRecord.value = record
  showDetailDialog.value = true
}

const generateSQL = async (record) => {
  selectedRecord.value = record
  
  try {
    // 调用后端API生成SQL
    const response = await api.result.generateCleanSQL(record.id, cleanAction.value)
    generatedSQL.value = response.data
    showSQLDialog.value = true
  } catch (error) {
    console.error('生成SQL失败:', error)
    // 如果API调用失败，回退到本地生成
    updateGeneratedSQL()
    showSQLDialog.value = true
  }
}

const updateGeneratedSQL = () => {
  if (!selectedRecord.value) return
  
  const { tableName, columnName, recordId, keyword } = selectedRecord.value
  
  switch (cleanAction.value) {
    case 'replace':
      generatedSQL.value = `UPDATE ${tableName} SET ${columnName} = REPLACE(${columnName}, '${keyword}', '***') WHERE id = ${recordId};`
      break
    case 'delete':
      generatedSQL.value = `DELETE FROM ${tableName} WHERE id = ${recordId};`
      break
    case 'clear':
      generatedSQL.value = `UPDATE ${tableName} SET ${columnName} = '' WHERE id = ${recordId};`
      break
  }
}

const ignoreResult = async (id) => {
  try {
    await ElMessageBox.confirm(t('sensitive.confirmIgnore'), t('sensitive.confirmIgnoreTitle'), { type: 'warning' })
    
    // 调用后端API忽略结果
    await api.result.ignoreResult(id, '用户手动忽略')
    
    // 从前端数组中移除
    checkResults.value = checkResults.value.filter(r => r.id !== id)
    ElMessage.success(t('sensitive.ignoreSuccess'))
  } catch (error) {
    if (error.message) {
      ElMessage.error(t('sensitive.ignoreFailed') + '：' + error.message)
    }
    // 如果是用户取消，不显示错误
  }
}

// 批量操作相关方法
const handleSelectionChange = (selection) => {
  selectedResults.value = selection
}

const batchIgnoreSelected = async () => {
  if (selectedResults.value.length === 0) {
    ElMessage.warning(t('sensitive.pleaseSelectResults'))
    return
  }
  
  try {
    await ElMessageBox.confirm(t('sensitive.confirmBatchIgnore', { count: selectedResults.value.length }), t('sensitive.batchIgnoreTitle'), { type: 'warning' })
    
    const ids = selectedResults.value.map(r => r.id)
    await api.result.batchIgnore(ids, '批量忽略操作')
    
    // 从前端数组中移除
    const ignoredIds = new Set(ids)
    checkResults.value = checkResults.value.filter(r => !ignoredIds.has(r.id))
    selectedResults.value = []
    
    ElMessage.success(t('sensitive.batchIgnoreSuccess', { count: ids.length }))
  } catch (error) {
    if (error.message) {
      ElMessage.error(t('sensitive.batchIgnoreFailed') + '：' + error.message)
    }
  }
}

const batchGenerateSQL = async () => {
  if (selectedResults.value.length === 0) {
    ElMessage.warning(t('sensitive.pleaseSelectResultsForSQL'))
    return
  }
  
  try {
    const ids = selectedResults.value.map(r => r.id)
    const response = await api.result.batchGenerateCleanSQL(ids, cleanAction.value)
    
    const sqlContent = response.data.join('\n')
    generatedSQL.value = sqlContent
    selectedRecord.value = { multiple: true, count: ids.length }
    showSQLDialog.value = true
  } catch (error) {
    ElMessage.error(t('sensitive.batchGenerateSQLFailed') + '：' + error.message)
  }
}

const exportResultsFile = async () => {
  if (!selectedTaskId.value) {
    ElMessage.warning(t('sensitive.pleaseSelectTask'))
    return
  }
  
  try {
    const response = await api.result.exportResults(selectedTaskId.value, 'csv')
    
    // 创建下载链接
    const blob = new Blob([response.data], { type: 'text/csv;charset=utf-8' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `敏感词检查结果_任务${selectedTaskId.value}_${new Date().toISOString().slice(0, 10)}.csv`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success(t('sensitive.exportSuccess'))
  } catch (error) {
    ElMessage.error(t('sensitive.exportFailed') + '：' + error.message)
  }
}

const showStatistics = async () => {
  if (!selectedTaskId.value) {
    ElMessage.warning(t('sensitive.pleaseSelectTask'))
    return
  }
  
  try {
    const response = await api.result.getResultStatistics(selectedTaskId.value)
    const stats = response.data
    
    ElMessageBox.alert(`
      <div style="text-align: left;">
        <p><strong>${t('sensitive.statisticsTitle')}</strong></p>
        <p>${t('sensitive.totalResults')}：${stats.totalResults}</p>
        <p>${t('sensitive.highRiskResults')}：${stats.highRiskResults}</p>
        <p>${t('sensitive.pendingResults')}：${stats.pendingResults}</p>
        <p>${t('sensitive.processedResults')}：${stats.processedResults}</p>
      </div>
    `, t('sensitive.statisticsTitle'), {
      dangerouslyUseHTMLString: true
    })
  } catch (error) {
    ElMessage.error(t('sensitive.getStatisticsFailed') + '：' + error.message)
  }
}

const copySQL = (sql) => {
  navigator.clipboard.writeText(sql)
  ElMessage.success(t('sensitive.copiedToClipboard'))
}

const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${mins}:${secs.toString().padStart(2, '0')}`
}

const getTagType = (category) => {
  const types = {
    '不文明词语': 'danger',
    '政治敏感': 'warning',
    '违法违规': 'danger',
    '商业敏感': 'info',
    '歧视言论': 'warning',
    '网络暴力': 'danger',
    '医疗违规': 'warning'
  }
  return types[category] || 'info'
}

const handleFileImport = async (file) => {
  try {
    const response = await api.sensitiveWord.batchImport(file)
    ElMessage.success(t('sensitive.importSuccess', { count: response.data.imported }))
    loadKeywords()
  } catch (error) {
    ElMessage.error(t('sensitive.importFailed'))
  }
  return false // 阻止默认上传
}

const exportKeywords = () => {
  const csv = convertToCSV(keywords.value)
  downloadCSV(csv, 'sensitive_keywords.csv')
}

const exportResults = () => {
  const csv = convertResultsToCSV(checkResults.value)
  const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-')
  downloadCSV(csv, `敏感词检查结果_${timestamp}.csv`)
}

const convertResultsToCSV = (data) => {
  if (!data.length) return ''
  
  // 定义中文列名和对应字段的映射
  const columnMapping = {
    '表名': 'tableName',
    '字段名': 'columnName', 
    '记录ID': 'recordId',
    '敏感词': 'keyword',
    '分类': 'category',
    '上下文': 'context',
    '处理状态': 'processStatus',
    '发现时间': 'createdAt',
    '数据库名': 'databaseName',
    '查询SQL': 'sqlQuery',
    '完整内容': 'fullContent'
  }
  
  // 生成CSV头部（中文列名）
  const headers = Object.keys(columnMapping)
  const headerRow = headers.join(',')
  
  // 生成数据行
  const rows = data.map(item => {
    return headers.map(header => {
      const fieldName = columnMapping[header]
      let value = item[fieldName] || ''
      
      // 特殊处理日期格式
      if (fieldName === 'createdAt' && value) {
        value = new Date(value).toLocaleString('zh-CN')
      }
      
      // 特殊处理长文本，截取前100个字符
      if (fieldName === 'fullContent' && value && value.length > 100) {
        value = value.substring(0, 100) + '...'
      }
      
      // 处理换行符和引号
      value = String(value).replace(/\n/g, ' ').replace(/"/g, '""')
      return `"${value}"`
    }).join(',')
  })
  
  return [headerRow, ...rows].join('\n')
}

const convertToCSV = (data) => {
  if (!data.length) return ''
  
  const headers = Object.keys(data[0])
  const rows = data.map(item => headers.map(header => `"${item[header] || ''}"`).join(','))
  return [headers.join(','), ...rows].join('\n')
}

const downloadCSV = (csv, filename) => {
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = filename
  link.click()
}

const clearResults = () => {
  checkResults.value = []
  selectedTaskId.value = null
  ElMessage.success(t('sensitive.resultsCleared'))
}

// 历史任务相关方法
const loadHistoryTasks = async () => {
  try {
    console.log('📋 加载历史任务...')
    const response = await api.checkTask.getTasks({
      current: 1,
      size: 20,
      status: '', // 获取所有状态的任务
      keyword: ''
    })
    historyTasks.value = response.data.records || []
    console.log(`✅ 成功加载 ${historyTasks.value.length} 个历史任务`)
  } catch (error) {
    console.error('❌ 历史任务加载失败:', error)
    // 如果API不存在，不抛出错误
    if (error.response?.status === 404) {
      console.log('📋 历史任务API暂未实现，跳过加载')
      return
    }
    throw error // 其他错误让上层处理
  }
}

const selectTask = async (task) => {
  // 确保taskId作为字符串处理，避免JavaScript数字精度问题
  const taskIdStr = String(task.taskId)
  selectedTaskId.value = taskIdStr
  
  // 总是尝试加载检查结果，不管状态
  try {
    const response = await api.result.getByTaskId(taskIdStr)
    
    const results = response.data || []
    checkResults.value = results
    
    // 滚动到结果区域（如果有结果）
    if (results.length > 0) {
      ElMessage.success(t('sensitive.taskLoadSuccess', { name: task.taskName, count: results.length }))
      // 延迟滚动到结果表格
      nextTick(() => {
        const resultsElement = document.querySelector('.results-card')
        if (resultsElement) {
          resultsElement.scrollIntoView({ behavior: 'smooth', block: 'start' })
        }
      })
    } else {
      if (task.status === 'COMPLETED') {
        ElMessage.success(t('sensitive.taskCompletedNoIssues', { name: task.taskName }))
      } else if (task.status === 'RUNNING') {
        ElMessage.info(t('sensitive.taskRunning', { name: task.taskName }))
      } else if (task.status === 'FAILED') {
        ElMessage.warning(t('sensitive.taskFailed', { name: task.taskName }))
      } else {
        ElMessage.info(t('sensitive.taskNoResults', { name: task.taskName }))
      }
    }
    
  } catch (error) {
    console.error('❌ 加载任务结果失败:', error)
    checkResults.value = []
    ElMessage.error(t('sensitive.taskLoadFailed', { name: task.taskName }))
  }
}

const getTaskStatusType = (status) => {
  const statusMap = {
    'PENDING': 'info',
    'RUNNING': 'warning', 
    'COMPLETED': 'success',
    'FAILED': 'danger',
    'CANCELLED': 'info'
  }
  return statusMap[status] || 'info'
}

const getTaskStatusText = (status) => {
  const statusMap = {
    'PENDING': t('sensitive.statusPending'),
    'RUNNING': t('sensitive.statusRunning'),
    'COMPLETED': t('sensitive.statusCompleted'), 
    'FAILED': t('sensitive.statusFailed'),
    'CANCELLED': t('sensitive.statusCancelled')
  }
  return statusMap[status] || status
}


const formatTaskTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) { // 1分钟内
    return t('sensitive.justNow')
  } else if (diff < 3600000) { // 1小时内
    return t('sensitive.minutesAgo', { n: Math.floor(diff / 60000) })
  } else if (diff < 86400000) { // 1天内
    return t('sensitive.hoursAgo', { n: Math.floor(diff / 3600000) })
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}


// 监听器
watch(cleanAction, updateGeneratedSQL)

// 页面初始化状态
const isInitialized = ref(false)
const isInitializing = ref(false)

// 统一的初始化方法
const initializePage = async () => {
  // 防止重复初始化
  if (isInitializing.value || isInitialized.value) {
    console.log('⚠️ 页面正在初始化中或已初始化，跳过重复调用')
    return
  }
  
  isInitializing.value = true
  console.log('🚀 敏感词管理页面开始初始化...')
  
  try {
    // 1. 先加载分类（同步方式，确保成功）
    console.log('1️⃣ 加载分类数据...')
    await initializeCategories()
    
    // 2. 然后加载其他数据（并行处理，提高效率）
    console.log('2️⃣ 并行加载其他数据...')
    const loadPromises = [
      loadKeywords().catch(err => console.warn('敏感词加载失败:', err)),
      loadDatabases().catch(err => console.warn('数据库加载失败:', err)),
      loadHistoryTasks().catch(err => console.warn('历史任务加载失败:', err))
    ]
    
    await Promise.allSettled(loadPromises)
    
    isInitialized.value = true
    console.log('✅ 页面初始化完成')
    
  } catch (error) {
    console.error('❌ 页面初始化失败:', error)
  } finally {
    isInitializing.value = false
  }
}

// 分类初始化（确保成功）
const initializeCategories = async () => {
  try {
    console.log('开始加载分类数据...')
    const response = await api.test.configCheck()
    
    if (response.data && response.data.categories) {
      categories.value = response.data.categories
      if (categories.value.length > 0 && !selectedCategory.value) {
        selectedCategory.value = categories.value[0]
      }
      console.log('✅ 成功加载分类:', categories.value)
    } else {
      throw new Error('后端未返回有效分类数据')
    }
  } catch (error) {
    console.warn('⚠️ 从后端加载分类失败，使用默认分类:', error)
    // 使用默认分类
    categories.value = ['不文明词语', '政治敏感', '违法违规', '商业敏感', '歧视言论', '网络暴力', '医疗违规']
    selectedCategory.value = categories.value[0]
    console.log('✅ 使用默认分类:', categories.value)
  }
}

// 生命周期
onMounted(() => {
  // 使用nextTick确保DOM完全挂载后再初始化
  nextTick(() => {
    initializePage()
  })
})

// 组件卸载时的清理
onUnmounted(() => {
  console.log('🧹 敏感词管理页面卸载，清理状态...')
  // 重置初始化状态
  isInitialized.value = false
  isInitializing.value = false
})


// 表选择相关方法
const loadTables = async () => {
  if (!checkConfig.value.databaseId) {
    availableTables.value = []
    selectedTables.value = []
    return
  }
  
  loadingTables.value = true
  try {
    console.log('加载数据库表列表...')
    const response = await api.database.getTables(checkConfig.value.databaseId)
    console.log('表列表API响应:', response)
    
    // 应用表过滤
    const allTables = response.data || []
    availableTables.value = filterBusinessTables(allTables)
    
    // 清空之前的选择，让用户主动选择
    selectedTables.value = []
    
    ElMessage.success(t('sensitive.loadTablesSuccess', { count: availableTables.value.length }))
  } catch (error) {
    console.error('加载表列表失败:', error)
    ElMessage.error(t('sensitive.loadTablesFailed'))
    availableTables.value = []
  } finally {
    loadingTables.value = false
  }
}

const onDatabaseChange = () => {
  console.log('数据库变更:', checkConfig.value.databaseId)
  selectedTables.value = []
  if (checkConfig.value.mode === 'selective') {
    loadTables()
  }
}

const onModeChange = () => {
  console.log('检查模式变更:', checkConfig.value.mode)
  if (checkConfig.value.mode === 'selective' && checkConfig.value.databaseId) {
    loadTables()
    tableSelectionExpanded.value = ['tables'] // 展开表选择
  } else {
    selectedTables.value = [] // 清空选择的表
  }
}


</script>

<style scoped src="@/styles/SensitiveWord.scss"></style>